package com.lb.shopguide.ui.fragment.guide.miji;

import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.MijiBean;
import com.lb.shopguide.event.guide.MijiLikeEvent;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2017/6/7.
 * h5页面
 */

public class FragmentMijiDetail extends BaseCommonFragment {
    @BindView(R.id.webView)
    BridgeWebView mWebView;
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.chk_fav)
    CheckBox chkFav;
    @BindView(R.id.tv_fav_num)
    TextView tvFav;
    @BindView(R.id.layout_fav)
    RelativeLayout layoutFav;

    private String webUrl;
    private String mijiCode;
    private String title;
    private MijiBean mijiBean;


    public static FragmentMijiDetail newInstance(String url, String mijiCode, String title) {
        FragmentMijiDetail fragmentMijiDetail = new FragmentMijiDetail();
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.WEB_URL, url);
        bundle.putString(AppConstant.MIJI_CODE, mijiCode);
        bundle.putString(AppConstant.WEB_TITLE, title);
        fragmentMijiDetail.setArguments(bundle);
        return fragmentMijiDetail;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_miji_detail;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.WEB_URL)) {
            webUrl = bundle.getString(AppConstant.WEB_URL);
        }
        if (bundle.containsKey(AppConstant.MIJI_CODE)) {
            mijiCode = bundle.getString(AppConstant.MIJI_CODE);
        }
        if (bundle.containsKey(AppConstant.WEB_TITLE)) {
            title = bundle.getString(AppConstant.WEB_TITLE);
        }
        sendRequestGetMijiInfo();
    }

    @Override
    public void initView() {


        ntb.setTitleText(title);
        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//把html中的内容放大webview等宽的一列中
        mWebView.getSettings().setBuiltInZoomControls(true); // 显示放大缩小
        mWebView.getSettings().setSupportZoom(true); // 可以缩放
        // 进度条控制
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (progressBar != null) {
                    if (newProgress >= 100) {
                        progressBar.setVisibility(View.GONE);
                    } else {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                }
                super.onProgressChanged(view, newProgress);
            }

        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setDefaultHandler(new DefaultHandler());

        mWebView.loadUrl(webUrl);
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) _mActivity).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentMijiDetail.class.getName();
    }

    private void sendRequestPraiseMiji(String mijiCode) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    mijiBean.setLiked(!mijiBean.isLiked());
                    if (mijiBean.isLiked()) {
                        ToastUtils.showShort("点赞成功");
                        mijiBean.setEsoLikedNum(mijiBean.getEsoLikedNum() + 1);
                    } else {
                        ToastUtils.showShort("取消点赞成功");
                        mijiBean.setEsoLikedNum(mijiBean.getEsoLikedNum() - 1);
                    }
                    bindLike();
                    EventBus.getDefault().post(new MijiLikeEvent(mijiBean));
                }
            }
        };
        ApiMethodGuide.praiseMiji(new SimpleLbObserver(listener, otherListener), mUserConfigManager.getUserId(), mijiCode, null, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetMijiInfo() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    mijiBean = (MijiBean) JsonUtil.getObject(response.getReturnContent(), MijiBean.class);
                    if (mijiBean != null) {
                        bindLike();
                    }
                }
            }
        };
        ApiMethodGuide.getMijiInfo(new SimpleLbObserver(listener, otherListener), mijiCode, this, FragmentEvent.DESTROY_VIEW);
    }

    private void bindLike() {
        if (chkFav != null) {
            chkFav.setChecked(mijiBean.isLiked());
            tvFav.setText("" + mijiBean.getEsoLikedNum());
        }
    }

    @OnClick(R.id.layout_fav)
    void fav() {
        if (mijiBean != null) {
            sendRequestPraiseMiji(mijiBean.getEsoCode());
        }
    }
}
